package org.currentcost.messages;

import java.util.*;

public class CostMessage
{
	private Map<Date, CostData> _costs;
	private static final String WHOLE_HOUSE = "0";
	private final String _sensorId;
	private EnviUnit _unit;
	private SensorData.SensorType _sensorType;

	public CostMessage(EnviMessage msg, String sensorId)
	{
		_sensorId = ( sensorId == null) ? WHOLE_HOUSE : sensorId;
		_costs = new HashMap<Date, CostData>();
		_init(msg);
	}

	private void _init(EnviMessage msg)
	{
		GregorianCalendar dayCal = new GregorianCalendar();
		_sensorType = msg.getSensorData().getSensorType();
		ValueData[] points = msg.getSensorData().getDataPoints();
		for (ValueData point : points) {
			if (_sensorId.equals(point.sensorId)) {
				if (_unit == null) {
					_unit = point.unit;
				}
				else if (point.unit != _unit) {
					throw new IllegalArgumentException("Incompatible units");
				}
				dayCal.setTime(point.startDate);
				int hour = dayCal.get(Calendar.HOUR_OF_DAY);
				boolean lowPrice = (hour >= 23 || hour < 7);
				dayCal.set(Calendar.HOUR_OF_DAY, 0);
				dayCal.set(Calendar.MINUTE, 0);
				dayCal.set(Calendar.SECOND, 0);

				Date dayTime = dayCal.getTime();
				CostData data = _costs.get(dayTime);
				if (data == null) {
					data = new CostData(dayTime, point.unit);
					_costs.put(dayTime, data);
				}
				data.addValue(lowPrice, point.value);
			}
		}
	}

	public CostData[] getCosts()
	{
		Collection<CostData> values = _costs.values();
		return values.toArray(new CostData[values.size()]);
	}

	public String getSensorId()
	{
		return _sensorId;
	}

	public SensorData.SensorType getSensorType()
	{
		return _sensorType;
	}

	public EnviUnit getUnit()
	{
		return _unit;
	}
}
